<?php
class File
{
	private $Table;
	private $type;
	public function __construct($type)
	{
		$this->Table = new Zend_Db_Table('files');
		$this->type= $type;
	} 
	
	
    public function downloadFile($Path)
      {
        $Config = Zend_Registry::get('config');
        $filename = $Config->file_path . DIRECTORY_SEPARATOR . $Path;
        if (!file_exists($filename)) return false;
        
        
        $Row = $this->Table->fetchRow( $this->Table->select()->where('Path = ?',$Path) );
        if (!$Row) return;
        
        
      	
      	$RealName = $Row->Name;

//      	$pathinfo  = pathinfo($RealName); 
//      	$extension = $pathinfo['extension'];
      	
      	$mimetype='application/octet-stream';
      	if (!file_exists($filename)) die('Файл не найден ' . $filename);
    
        $from=$to=0; $cr=NULL;
    
        /*if (isset($_SERVER['HTTP_RANGE']))
        {
          $range=substr($_SERVER['HTTP_RANGE'], strpos($_SERVER['HTTP_RANGE'], '=')+1);
          $from=strtok($range, '-');
          $to=strtok('/'); if ($to>0) $to++;
          if ($to) $to-=$from;
          header('HTTP/1.1 206 Partial Content');
          $cr='Content-Range: bytes ' . $from . '-' . (($to)?($to . '/' . $to+1):filesize($filename));
        } else  header('HTTP/1.1 200 Ok');
    */
        /*$etag=md5($filename);
        $etag=substr($etag, 0, 8) . '-' . substr($etag, 8, 7) . '-' . substr($etag, 15, 8);
        header('ETag: "' . $etag . '"');*/
    
      //  header('Accept-Ranges: bytes');
        header('Content-Length: ' . (filesize($filename)));
        if ($cr) header($cr);
    
        header('Connection: close');
        header('Content-Type: ' . $mimetype);
        header('Last-Modified: ' . gmdate('r', filemtime($filename)));
        $f=fopen($filename, 'r');
        header('Content-Disposition: attachment; filename="' . $RealName  . '";');
       // if ($from) fseek($f, $from, SEEK_SET);
        /*if (!isset($to) or empty($to))
        {
          $size=filesize($filename)-$from;
        }
        else
        {
          $size=$to;
        }*/
        $size=filesize($filename);
        $downloaded=0;
    
        while(!feof($f) and !connection_status() and ($downloaded<$size)) {
          echo fread($f, 512000);
          $downloaded+=512000;
          flush();
        }
        fclose($f);
        return true;
      }
	
	public function get($id)
	{
		 $Rows = $this->Table->fetchAll( $this->Table->select()->where('itemId = ' . intval($id)) );
		 if ($Rows) return $Rows->toArray();
		 return array();
	} 
	
	
    public function uploadFile($Name,$CategoryID)
	{
		$Config = Zend_Registry::get('config');
        $filesPath = $Config->file_path . DIRECTORY_SEPARATOR;
        
       if (!isset($_FILES[$Name])) throw new Exception("File $Name not found in registry", 7001);

       $tmpName =  $_FILES[$Name]['tmp_name'];
       $fileName =  $_FILES[$Name]['name'];
       
       $newFileName = md5($fileName . time()) . "-" . time();
        
       Logger::log($tmpName);
       Logger::log($filesPath . $newFileName);
       
       
       copy($tmpName, $filesPath . $newFileName);
       
       $this->insert($CategoryID, $fileName, $newFileName);
	}
	
	
	public function insert($CategoryID,$Name,$Path)
	{
		$Row = $this->Table->createRow(array('itemId'=>$CategoryID,'Name'=>$Name,'Path'=>$Path));
		$Row->save();
		return  $Row->ID;
	}
	
	public function rename($FID, $Name)
	{
		$this->Table->update(array('Name'=>$Name)," ID = " . intval($FID));
	}
	
    public function remove($FID)
    {
        $Row = $this->Table->find($FID);
        if ($Row)
        {
            $Row = $Row->current();
        	$Config = Zend_Registry::get('config');
            unlink($Config->file_path . DIRECTORY_SEPARATOR . $Row->Path);
            $Row->delete();	
        }
    }
    
    public function removeByCategory($FID)
    {
        $Row = $this->Table->fetchRow($this->Table->select()->where('itemId = ?',$FID));
        if ($Row)
        {
        	$Config = Zend_Registry::get('config');
            unlink($Config->file_path . DIRECTORY_SEPARATOR . $Row->Path);
            $Row->delete();	
        }
    }

}